<?php

namespace app\controller\admin\ec;


use think\Request;
use \think\facade\Validate;
use app\eslib\EsUtils;
use app\model\ec\AttributesModel;
use app\model\ec\BrandsModel;
use app\model\ec\CategoriesModel;
use app\model\ec\GoodsModel;
use app\model\ec\SpecificationsModel;
use app\model\ec\TagsModel;

class Goods
{

    /**
     * 构造方法
     */
    public function __construct()
    {
        // $this->middleware('jwtauth.admin');
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $categoryId = $request->param('category_id', 0);
        $searchText = $request->param('search_text', '');
        $pageSize = intval($request->param('page_size', 10));

        $data = GoodsModel::dbView()->where(function ($query) use ($categoryId, $searchText) {
            if ($categoryId > 0) {
                $query->where('category_id', $categoryId);
            }
            if ($searchText) {
                $query->where(function ($query) use ($searchText) {
                    $query->where('id', intval($searchText))->whereOr('goods_name', 'like', "%{$searchText}%");
                });
            }
        })->order('id', 'desc')->append(['status_text'])->paginate($pageSize);

        return json(EsUtils::stdMessage(true, '', $data));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->all();
        $validator = Validate::rule([
            'category_id' => 'required|numeric',
            'goods_name' => 'required|max:150',
            'icon' => 'required|max:150',
        ], [
            'required' => ':attribute 必须填写',
            'numeric' => ':attribute 必须是数值',
            'max' => ':attribute 不能超过 :max 个字符',
        ], [
            'category_id' => '商品分类',
            'goods_name' => '商品名称',
            'icon' => '商品图片'
        ]);
        if (!$validator->check($formData)) {
            return json(EsUtils::stdMessage(false, $validator->getError()));
        }
        // 表单数据处理
        // ...
        try {
            $model = GoodsModel::create($formData);
            return json(EsUtils::stdMessage(true, '', $model->id));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage()));
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read(Request $request, $id)
    {
        if (!is_numeric($id)) {
            return json(EsUtils::stdMessage(false, 'id值无效', $id));
        }
        $categoryId = 0;
        $specIds = [];
        $mode = $request->param('_mode', '');
        if ($id > 0) {
            $model = GoodsModel::find($id);
            if (!$model) {
                return json(EsUtils::stdMessage(false, '记录不存在'));
            }
            $categoryId = $model->category_id;
            if ($model->spec_data) {
                $specIds = json_decode($model->spec_data);
            }
        } else {
            $model = new GoodsModel();
            $model->status = 1;
        }
        $data = [
            'data' => $model,
        ];
        switch ($mode) {
            case 'tags':
                $data['tags_data'] = TagsModel::getDictData($categoryId);
                break;
            case 'attrs':
                $data['attrs_data'] = AttributesModel::getDictData($categoryId);
                break;
            case 'sku':
                // 编辑商品规格SKU
                $data['specs_data'] = SpecificationsModel::getTreeList($categoryId);
                $data['skus_data'] = SkusModel::getSkuList($id);
                break;
            case 'sku-preview':
                // 预览商品规格SKU
                $data['specs_data'] = SpecificationsModel::getTreeList($categoryId, $specIds);
                $data['skus_data'] = SkusModel::getSkuList($id);
                break;
            case 'sku-check':
                // 获取商品规格SKU（用于前端勾选，显示缺货信息）
                $skuNo = $request->param('sku_no', []);
                if (!is_array($skuNo)) {
                    $skuNo = explode(',', $skuNo);
                }
                $data['skus_data'] = SkusModel::getSkuList($id, $skuNo);
                $data['skus_quantity'] = SkusModel::getSkuQuantity($id, $skuNo);
                break;
            case 'onlydata':
                break;
            default:
                $data['category_id_data'] = CategoriesModel::getDictData();
                $data['brand_id_data'] = BrandsModel::getDictData($categoryId);
                $data['status_data'] = $model->getStatusDataAttr();
                break;
        }
        return json(EsUtils::stdMessage(true, $id, $data));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        // 特殊模式的更新操作
        $mode = $request->param('_mode');
        switch ($mode) {
            case 'uoc':
                // uoc = update one field，更新指定字段的值
                $formData = $request->only(['tags_data', 'attrs_data']);
                break;
            case 'update-sku':
                $specData = $request->param('spec_data', '');
                $skuData = $request->param('sku_data', '');
                $formData = [];
                if ($specData) {
                    $formData = ['spec_data' => $specData];
                }
                try {
                    $affected = SkusModel::addRecords($id, $skuData);
                    if ($formData) {
                        $affected = GoodsModel::where('id', $id)->update($formData);
                    }
                    return json(EsUtils::stdMessage(true, '', $affected));
                } catch (\Exception $ex) {
                    return json(EsUtils::stdMessage(false, $ex->getMessage()));
                }
            default:
                $formData = $request->all();
                $validator = Validate::rule([
                    'category_id' => 'required|numeric',
                    'goods_name' => 'required|max:150',
                    'icon' => 'required|max:150',
                ], [
                    'required' => ':attribute 必须填写',
                    'numeric' => ':attribute 必须是数值',
                    'max' => ':attribute 不能超过 :max 个字符',
                ], [
                    'category_id' => '商品分类',
                    'goods_name' => '商品名称',
                    'icon' => '商品图片'
                ]);
                if ($validator->fails()) {
                    return json(EsUtils::stdMessage(false, $validator->errors(), $validator->errors()));
                }
                break;
        }
        try {
            $affected = GoodsModel::where('id', $id)->update($formData);
            return json(EsUtils::stdMessage(true, '', $affected));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage()));
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        try {
            $affected = GoodsModel::destroy($id);
            return json(EsUtils::stdMessage(true, '', $affected));
        } catch (\Exception $ex) {
            return json(EsUtils::stdMessage(false, $ex->getMessage()));
        }
    }
}
